package com.dsx.test.interceptor;

import com.dsx.test.properties.ShiroProperties;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author : tianwenqing
 * @version : 1.0
 * @date : 2020-11-16 17:27
 * @description :
 **/
@Component
public class InterceptorConfig implements WebMvcConfigurer {

    @Autowired
    private ShiroProperties shiroProperties;
    @Autowired
    private ShiroAuthenticationInterceptor shiroAuthenticationInterceptor;
    @Autowired
    private ShiroAuthorizationInteceptor shiroAuthorizationInteceptor;


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //是否开启shiro认证
        if (shiroProperties != null && shiroProperties.getEnabled()) {
            InterceptorRegistration jwtIR = registry.addInterceptor(shiroAuthenticationInterceptor);
            jwtIR.addPathPatterns(shiroProperties.getPathPatterns());

            //排除静态资源
            if (!CollectionUtils.isEmpty(shiroProperties.getAuthcExcludePathPatterns())) {
                jwtIR.excludePathPatterns(shiroProperties.getAuthcExcludePathPatterns());
            }
            //排除项目中设置的不需要认证的路径
            if (!CollectionUtils.isEmpty(shiroProperties.getAnonymous())) {
                jwtIR.excludePathPatterns(shiroProperties.getAnonymous());
            }

            //是否开启shiro授权
            if (shiroProperties.getPermEnabled()) {
                InterceptorRegistration permIR;
                permIR = registry.addInterceptor(shiroAuthorizationInteceptor);
                permIR.addPathPatterns(shiroProperties.getPathPatterns());

                //排除静态资源
                if (!CollectionUtils.isEmpty(shiroProperties.getAuthcExcludePathPatterns())) {
                    permIR.excludePathPatterns(shiroProperties.getAuthcExcludePathPatterns());
                }
                //排除项目中设置的不需要认证的路径
                if (!CollectionUtils.isEmpty(shiroProperties.getAnonymous())) {
                    permIR.excludePathPatterns(shiroProperties.getAnonymous());
                }

                if (!CollectionUtils.isEmpty(shiroProperties.getPermExcludePathPatterns())) {
                    permIR.excludePathPatterns(shiroProperties.getPermExcludePathPatterns());
                }

                //排除项目中设置的不需要授权的路径
                if (!CollectionUtils.isEmpty(shiroProperties.getPermAnonymous())) {
                    permIR.excludePathPatterns(shiroProperties.getPermAnonymous());
                }


            }

        }

    }
}
